import "reflect-metadata";
import { createConnection } from "typeorm";
import { isObject } from "util";
import { Request, Response } from "express";
import { Mail } from "../entity/Mail";
import { Role } from "../entity/Role";
import { Attachment } from "../class/Attachment";
import { items } from "../configs/configs";

let moment = require('moment-timezone');

const GM = 2;
const conn = createConnection("mail");
const connR = createConnection("role");

function mapToAttachment(map: object): Attachment {

    let attachment = new Attachment;
    for (let ID in map) {
        attachment.addRawItem(Number(ID), map[ID]);
    }

    return attachment;
}

export function mailRoute(app: any) {

    app.put('/api/mail/role/:role_id', function (req: Request, res: Response) {

        let attachment = null;
        if (req.body.attachment) {
            let map = JSON.parse(req.body.attachment);
            if (map && !isObject(map)) {
                res.send({ success: false, msg: "附件格式错误" });
                return
            }

            if (map && map != {}) {

                for (let ID in map) {
                    if (!items[ID]) {
                        res.send({ success: false, msg: "道具ID错误" });
                        return
                    }

                    if (!Number(map[ID]) || map[ID] < 1 || map[ID] > 99999999) {
                        res.send({ success: false, msg: "道具数量错误" });
                        return
                    }
                }

                attachment = mapToAttachment(map);
            }
        }

        connR.then(async connection => {

            let role = await connection.getRepository(Role).findOne(Number(req.params.role_id));
            if (!role) {
                res.send({ success: false, msg: "角色ID错误" });
                return
            }

            let mail = new Mail();
            mail.role_id = Number(req.params.role_id);
            mail.from_type = GM;
            mail.title = req.body.title
            mail.content = req.body.content;
            mail.read = false;
            mail.created_at = moment().format();
            mail.updated_at = mail.created_at;

            if (attachment) {
                mail.attachment = attachment;
            }

            (await conn).getRepository(Mail).save(mail);
            res.send({ success: true });

        }).catch(error => res.send({ success: false, msg: error }));
    })

    app.put('/api/mail/server/:server_id', function (req: Request, res: Response) {

        let attachment = null;
        if (req.body.attachment) {
            let map = JSON.parse(req.body.attachment);

            if (map && map != {}) {

                for (let ID in map) {
                    if (!items[ID]) {
                        res.send({ success: false, msg: "道具ID错误" });
                        return
                    }

                    if (!Number(map[ID]) || map[ID] < 1 || map[ID] > 99999999) {
                        res.send({ success: false, msg: "道具数量错误" });
                        return
                    }
                }

                attachment = mapToAttachment(map);
            }
        }

        connR.then(async connection => {

            let where = {};
            if (Number(req.params.server_id) > 0) {
                where = { where: { server_id: req.params.server_id } };
            }

            let time = moment().format();
            let values: Mail[] = [];

            let roles = await connection.getRepository(Role).find(where);

            roles.forEach(element => {

                let mail = new Mail();
                mail.role_id = element.role_id;
                mail.from_type = GM;
                mail.title = req.body.title
                mail.content = req.body.content;
                mail.read = false;
                mail.created_at = time;
                mail.updated_at = mail.created_at;

                if (attachment) {
                    mail.attachment = attachment;
                }

                values.push(mail);
            });

            conn.then(async connection => {
                await connection.createQueryBuilder().insert().into(Mail).values(values).execute();
                res.send({ success: true });
            }).catch(error => res.send({ success: false, msg: error }));
        })
    });

    app.get('/mail', function (req: Request, res: Response) {

        res.render('mail/mail')
    })

    app.get('/mail/server', function (req: Request, res: Response) {

        res.render('mail/server')
    })

    app.get('/mail/role', function (req: Request, res: Response) {

        res.render('mail/role')
    })
}
